<template>
	<view class="login-model">
		<view class="title-modal">
			<view class="title-h2">用户名密码登录</view>
			<view class="title-description">
				未注册的手机号验证通过后即可完成注册
			</view>
		</view>
		<up-form ref="LoginFormRef" :model="pageData.loginForm" :rules="rules">
			<up-form-item prop="username">
				<up-input v-model="pageData.loginForm.username" placeholder="请输入用户名" border="bottom"
					clearable></up-input>
			</up-form-item>
			<up-form-item prop="password">
				<up-input v-model="pageData.loginForm.password" placeholder="请输入密码" border="bottom" type="password"
					clearable></up-input>
			</up-form-item>
			<up-form-item prop="captcha">
				<up-input v-model="pageData.loginForm.captcha" placeholder="请输入图形验证码" border="bottom"
					clearable></up-input>
			</up-form-item>
			<view class="img-code" v-html="imgCode"></view>
			<!-- <rich-text style="height: 80rpx;width: 200rpx;" :nodes="imgCode"></rich-text> -->
			<up-button type="primary" shape="circle" size="small" @click="doLogin">登录</up-button>
		</up-form>
	</view>
</template>

<script setup>
	import {ACCESS_LOGIN, GET_CAPTCHA} from '@/api/login.js'
	import {
		reactive, ref
	} from 'vue';
	const LoginFormRef = ref(null)
	const pageData = reactive({
		loginForm: {
			username: '',
			password: '',
			captcha:''
		}
	})
	const imgCode = ref('')
	const getCaptcha = () => {
		GET_CAPTCHA().then(res => {
			imgCode.value = res
			console.log(res)
		})
	}
	getCaptcha()
	const rules = {
		'username': {
			type: 'string',
			required: true,
			message: '请输入用户名',
			trigger: ['blur', 'change'],
		},
		"password": [{
			pattern: /^\d+$/,
			required: true,
			message: '请输入正确密码',
			trigger: ['blur', 'change'],
		},{
			validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return value.length>=6
						},
						message: '密码必须大于6位',
						// 触发器可以同时用blur和change
						trigger: ['change','blur'],
		}]
	}
	const doLogin = () => {
		LoginFormRef.value.validate().then(valid => {
			if(valid) {
				//掉接口登录
				console.log(pageData.loginForm)
				const params = {
					username: pageData.loginForm.username,
					password: pageData.loginForm.password,
					captcha: pageData.loginForm.captcha
				}
				ACCESS_LOGIN(params).then(res => {
					//获取到一个token
					const token =res.token
					uni.setStorageSync('token',token)
					//跳转到业务内部页面
				})
			} else {
				uni.$u.toast('校验失败')
			}
		})
	}
</script>

<style lang="scss">
.login-model{
	width: 90%;
	margin: 50rpx auto 0;
}
</style>